package com.neaten.functionArrangement.util;


import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.io.MemoryUsageSetting;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
import org.apache.pdfbox.multipdf.Splitter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.pdfbox.text.PDFTextStripper;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

@Slf4j
@UtilityClass
public class PdfUtil {

    /**
     * 删除pdf的部分页
     * @param pdfPath
     * @param startIdx 开始页码，页码从0开始
     * @param endIdx
     */
    public void cutPdf(String pdfPath,int startIdx,int endIdx) {
        File file = new File(pdfPath);
        PDDocument document = new PDDocument();
        try {
            document = PDDocument.load(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        int noOfPages = document.getNumberOfPages();
        System.out.println(noOfPages);
        for (int i = startIdx; i <= endIdx; i++) {
            document.removePage(i);
        }
        try {
            document.save(pdfPath);
            document.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * pdf转图片
     *
     * @param filePath
     * @param outputPath
     * @param fileName
     * @param startIdx   开始页，页码从0 开始
     * @param endIdx     结束页
     * @return
     */
    public static String pdf2pngOfGraphPaperPdf(String filePath, String outputPath, String fileName, int startIdx, int endIdx) {

        String type = "png";
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(filePath);
        List<String> list = new ArrayList<>();
        PDDocument doc = null;
        try {
            doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            for (int i = startIdx; i <= endIdx; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                ImageIO.write(image, type, new File(outputPath + "\\" + fileName + "-第" + (i + 1) + "页." + type));
            }
            BufferedImage image = renderer.renderImageWithDPI(0, 120); // Windows native DPI
            String pngFilePath = outputPath + fileName + "." + type;
            ImageIO.write(image, type, new File(pngFilePath));
            return pngFilePath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                doc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    /**
     * pdf转图片
     *
     * @param filePath
     * @param outputPath
     * @param fileName
     * @param startIdx   开始页，页码从0 开始
     * @param endIdx     结束页
     * @param cutOutX    截取pdf的左上角x坐标
     * @param cutOutY    截取pdf的右上角x坐标
     * @param cutOutW    截取pdf的宽
     * @param cutOutH    截取pdf的高
     * @return
     */
    public static List<String> pdf2pngOfGraphPaperPdf(String filePath, String outputPath, String fileName, int startIdx, int endIdx, int cutOutX, int cutOutY, int cutOutW, int cutOutH) {

        String type = "png";
        // 将pdf装图片 并且自定义图片得格式大小
        File file = new File(filePath);
        List<String> list = new ArrayList<>();
        PDDocument doc = null;
        List<String> resList = new ArrayList<>();
        try {
            doc = PDDocument.load(file);
            PDFRenderer renderer = new PDFRenderer(doc);
            for (int i = startIdx; i <= endIdx; i++) {
                BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI
                BufferedImage subimage = image.getSubimage(cutOutX, cutOutY, cutOutW, cutOutH);
                String pngFilePath = outputPath + "\\" + fileName + "-第" + (i + 1) + "页." + type;
                ImageIO.write(subimage, type, new File(pngFilePath));
                resList.add(pngFilePath);
            }
            return resList;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                doc.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    /**
     * pdf分解为多个pdf
     *
     * @param file
     * @param savePath
     * @return
     * @throws IOException
     */
    private List<String> pdfOne2Multipart(File file, String savePath) throws IOException {
        String fileName = file.getName();
        String filePre = fileName.substring(0, fileName.lastIndexOf("."));
        PDDocument document = PDDocument.load(file);
        Splitter splitter = new Splitter();
        List<PDDocument> pages = splitter.split(document);
        ListIterator<PDDocument> iterator = pages.listIterator();
        int i = 0;
        List<String> filePathList = new ArrayList<>();
        while (iterator.hasNext()) {
            String targetPath = savePath + filePre + Long.toHexString(System.currentTimeMillis()) + "-第" + ++i + "页.pdf";
            PDDocument pdf = iterator.next();
            pdf.save(targetPath);
            pdf.close();
            filePathList.add(targetPath);
        }
        document.close();
        return filePathList;
    }

    /**
     * 多个pdf文件合并为一个pdf文件
     *
     * @param fileList
     * @param targetPdf
     * @return
     */
    public File multiplePdf2One(List<File> fileList, String targetPdf) {
        PDFMergerUtility pdfMergerUtility = new PDFMergerUtility();
        for (File file : fileList) {
            if (file.exists() && file.isFile()) {
                try {
                    pdfMergerUtility.addSource(file);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        pdfMergerUtility.setDestinationFileName(targetPdf);
        try {
            pdfMergerUtility.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new File(targetPdf);
    }


    /**
     * 获取pdf中的文字
     *
     * @param inputStream
     * @return
     * @throws IOException
     */
    private String readPdf(InputStream inputStream) throws IOException {
        PDDocument document = PDDocument.load(inputStream);
        document.getClass();
        //使用PDFTextStripper 工具
        PDFTextStripper tStripper = new PDFTextStripper();
        //设置文本排序，有规则输出
        tStripper.setSortByPosition(true);
        //获取所有文字信息
        String info = tStripper.getText(document);
        return info;
    }
}
